package www.dianbaozu.com.ui.manage

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString

class GroupSortManagementViewModel @ViewModelInject constructor(appDataManager: AppDataManager) :
        BaseApiViewModel(appDataManager) {


    @FlowPreview
    fun requestGroupSort(
            body: List<RequestBodyParameter>,
            serverId: String,
            action: ((ServerGroupEntity) -> Unit),
    ) {
        viewModelScope.launch {
            appDataManager.groupSortFlow(body)
                    .flatMapConcat {
                        appDataManager.serverGroupListFlow(serverId)
                    }
                    .onStart {
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        getString(R.string.com_sorting),
                                        LoadingDialogStateType.LOADING
                                )
                        )
                    }
                    .onCompletion { cause ->
                        if (cause == null) {
                            loading.value = UiStateCustom(
                                    stateData = LoadingDialog(
                                            tip = "",
                                            loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                            isShowDialogTip = false,
                                            isShowToastTip = false
                                    )
                            )
                        }
                    }
                    .catch { cause ->
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        tip = cause.message ?: "网络异常",
                                        loadingDialogStateType = LoadingDialogStateType.ERROR,
                                        isShowDialogTip = false,
                                        isShowToastTip = true
                                )
                        )
                    }
                    .collect {
                        action.invoke(it.data)
                    }
        }
    }

}